package com.androidgame.framework.impl;

import java.io.IOException;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;

import com.androidgame.framework.Audio;
import com.androidgame.framework.Music;
import com.androidgame.framework.Sound;

public class AndroidAudio implements Audio 
{
	//Provides access to an application's raw asset files in the APK
	AssetManager assets;
	//load sound effects from asset files into the SoundPool
	SoundPool soundPool;

	public AndroidAudio(Activity activity) 
	{
		//set the volume control to the media stream
		activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
		
		//store in the corresponding member of the class
		this.assets = activity.getAssets();
		
		//SoundPool is configured to be able to play back 20 sound effects in parallel
		this.soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
	}

	//creates a new AndroidMusic instance
	public Music newMusic(String filename) 
	{
		try 
		{
			//load the music from an asset file
			AssetFileDescriptor assetDescriptor = assets.openFd(filename);
			
			//takes an AssetFileDescriptor, from which it creates a MediaPlayer
			return new AndroidMusic(assetDescriptor);
		} 
		
		catch (IOException e) 
		{
			throw new RuntimeException("Couldn't load music '" + filename + "'");
		}
	}

	//creates a new AndroidSound instance
	public Sound newSound(String filename) 
	{
		try 
		{
			//load the sound from an asset file
			AssetFileDescriptor assetDescriptor = assets.openFd(filename);
			
			//load sound into the pool returning an ID
			int soundId = soundPool.load(assetDescriptor, 0);
			
			//takes a SoundPool and the ID of the sound effect
			return new AndroidSound(soundPool, soundId);
		} 
		
		catch (IOException e) 
		{
			throw new RuntimeException("Couldn't load sound '" + filename + "'");
		}
	}
}